package main.adapter;

import java.util.ArrayList;
import java.util.Calendar;

import main.alarms.AlarmCloseMthodConf;
import main.alarms.AlarmInfo;
import main.alarms.R;
import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

public class AlarmsListAdapter extends BaseAdapter {
	private ArrayList<AlarmInfo> infos=new ArrayList<AlarmInfo>();
	private Context context;
	private LayoutInflater mInflater;
	public AlarmsListAdapter(Context context,ArrayList<AlarmInfo> infos){
		this.context=context;
		this.mInflater=LayoutInflater.from(this.context);
		for(int i=0;i<infos.size();i++){
			if(infos.get(i)!=null){
				this.infos.add(infos.get(i));
			}	
		}
		
	}

	@Override
	public int getCount() {
		return this.infos.size();
	}

	@Override
	public Object getItem(int position) {
		return this.infos.get(this.getCount()-position-1);
	}

	@Override
	public long getItemId(int position) {
		return this.infos.get(this.getCount()-position-1).id;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = new ViewHolder();
		if(convertView==null){
			convertView=this.mInflater.inflate(R.layout.alarm_list_item, null);
			holder.timeBtn=(Button) convertView.findViewById(R.id.timeBtn);
			holder.descriptionTxt=(TextView) convertView.findViewById(R.id.descriptionTxt);
			holder.weekDateTxt=(TextView) convertView.findViewById(R.id.weekDateTxt);
			holder.enabledCb=(CheckBox) convertView.findViewById(R.id.enabledCb);
			convertView.setTag(holder);
		}
		else{
			holder=(ViewHolder) convertView.getTag();
		}
		AlarmInfo info=(AlarmInfo)this.getItem(position);
		holder.timeBtn.setText(info.time.get(Calendar.HOUR_OF_DAY)+":"+info.time.get(Calendar.MINUTE));
		holder.descriptionTxt.setText(info.descriptin);
		holder.enabledCb.setChecked(info.enabled);
		holder.weekDateTxt.setText(Html.fromHtml(this.genWeekDateTxt(info.weekPerid)));
		return convertView;
	}
	private String genWeekDateTxt(int[] days){
		String[] weeks={"Su","M","Tu","W","Th","F","Sa"};
		String rst="";
		for(int i=0;i<7;i++){
			if(days[i]==1){
				rst+="<b>"+weeks[i]+"</b> ";
			}
			else{
				rst+=weeks[i]+" ";
			}
		}
		return rst;
	}
	
	private class ViewHolder{
		Button timeBtn;
		TextView descriptionTxt;
		TextView weekDateTxt;
		CheckBox enabledCb;
	}

}
